package cn.kgc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/14
 * @Description: cookie的基本使用
 */
@WebServlet("/ck")
public class CookieServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取请求中的cookie
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                System.out.println(name+":"+value);
            }
        }

        //  生成在服务端 保存在服务端
        String id = req.getSession().getId();
        System.out.println("id = " + id);

        String username = "tom";
        // 创建cookie对象    生成在服务端 保存在客户端
        Cookie cookie = new Cookie("username", username);
        // 设置cookie的存活时间
        cookie.setMaxAge(30);   // s
        // 绑定cookie      resp
        resp.addCookie(cookie);

        resp.sendRedirect(req.getContextPath()+"/ck.jsp");
    }
}
